package com.fkdx.webman.aspect;

import com.alibaba.fastjson.JSON;
import com.fkdx.common.dto.ResponseDTO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
//@Aspect
//@Component
public class ControllerAspect {

    public ControllerAspect() {
    }

    @Pointcut("execution(* com.fkdx.webman.controller.*.*(..))")
    public void validationPointCut() {}

    /**
     * @Description: 请求拦截
     * @Author: Jiang.Li
     * @Date: 2020/6/22
     */
    @Around(value="validationPointCut()", argNames="joinPoint")
    public Object aroundExecute(ProceedingJoinPoint joinPoint){
        //用于计算请求耗时
        long begin = System.currentTimeMillis();
        //返回信息
        Object result = null;
        try{
            result = joinPoint.proceed();
//            if (obj instanceof ResponseDTO){
//                result = obj;
//            } else {
//                result = ResponseDTO.buildSuccessDataResp(obj);
//            }
        }
//        catch (GroupException e){
//            log.error("业务异常", e);
//            result = ResponseDTO.buildErrorResp(e.getMessage());
//        }
        catch(Throwable e){
            log.error("系统异常", e);
            result = ResponseDTO.buildSysError(e.getMessage());
        }
        Object param = joinPoint.getArgs() == null || joinPoint.getArgs().length == 0 ? null : joinPoint.getArgs()[0];
        String printParam = null;
        if(param == null){
            printParam = "";
        }else if(param instanceof MultipartFile){
            printParam = ((MultipartFile) param).getOriginalFilename();
        }else{
            printParam = JSON.toJSONString(param);
        }
        log.info("接口调用成功,方法:[{}],参数:[{}],响应:[{}],耗时:[{}ms]",
                String.format("%s.%s",joinPoint.getTarget().getClass().getSimpleName(),joinPoint.getSignature().getName()),
                JSON.toJSONString(printParam),
                JSON.toJSONString(result),
                System.currentTimeMillis() - begin);
        return result;
    }

}
